package br.kanban.view.service;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ControleAcesso implements Filter{

	@Inject
	private Identity identity;
	
    private static final String LOGIN_PAGE = "/Kanban/";  
    
    public void init( FilterConfig filterConfig ) throws ServletException{  
    }  
  
    public void doFilter( ServletRequest req, ServletResponse res, FilterChain chain ) throws IOException, ServletException{
    	HttpServletResponse response = (HttpServletResponse)res;  
    	HttpServletRequest request = (HttpServletRequest)req;  
    	
//		HttpSession session = request.getSession(false);         
//		if(session != null){  
//			usuarioLogado = (Usuario) session.getAttribute("usuarioLogado");
//		}  
    	
        String pageDest = request.getRequestURI();
        System.out.println(pageDest);
//        System.out.println(usuarioLogado!=null? usuarioLogado.getNome() : "nulo");
     
        if( !this.authenticated()){  
            response.sendRedirect(LOGIN_PAGE );  
        }else if( !this.authorized(pageDest) ){
        	 throw new AcessoNegadoException("Você não possui acesso para acessar esta pagina"); 
        }else{
            //Desativa o cache do browser  
            response.setHeader("Cache-Control","no-store");  
            response.setHeader("Pragma","no-cache");  
            response.setDateHeader("Expires",0);  
            //Processa request e response  
            chain.doFilter( req, res );  
        }  
    }  
  
    public void destroy(){  
    }  

    private boolean authenticated(){  
    	return identity.getUsuarioLogado() != null && identity.getUsuarioLogado().getCodigo() != null;  
    } 

    private boolean authorized(String page){  
    	String[] pages = page.split("/");
    	page = pages.length > 3 ? pages[3] : "";
    	
    	return identity.rendered(page);  
    }  
    
}
